<?php
/**
 * Created by PhpStorm.
 * User: geolo
 * Date: 2018/10/10
 * Time: 10:50
 */
namespace app\modules\api\models;
use app\models\Goods;
use app\models\AgentGood;
use app\models\Store;
use yii\data\Pagination;
/**
 * @property AgentGood $model
 * @property Store $store
 */
class AgentGoodForm extends Model
{
    public $model;
    public $store_id;
    public $pingtai_id;
    public $pagesize;
    public $pages;
    public $good;


    public function rules()
    {
        return [
            [['store_id', 'pagesize','pages','pingtai_id'], 'integer'],
            [['good'],'string'],
            [['store_id'],'required']
        ];
    }
    public function attributeLabels()
    {
        return [
            'store_id' => 'Store ID',
            'good' => '选择商品',
            'pingtai_id'=>'平台ID',
        ];
    }

    public function getdata()
    {
        $query = Goods::find()->select('id,cover_pic,name,price')->where(['store_id'=>$this->pingtai_id,'is_delete'=>0,'status'=>1]);
        $count = $query->count();
        $pages = new Pagination(['totalCount'=>$count,'pageSize'=>$this->pagesize]);
        $offest = ($this->pages-1)*$this->pagesize;
//        $list = $query->limit($page,$this->pagesize)->asArray()->all();
        $list = $query->offset($offest)
            ->limit($this->pagesize)
            ->asArray()->all();
        $res = AgentGood::find()->where(['store_id'=>$this->store_id])->asArray()->all();
//        echo count($list);
//        echo $query->createCommand()->getRawSql();
        $agent = explode(',',$res[0]['good']);
        foreach($list as $key =>$value){
            $list[$key]['type']=0;
            for($i=0;$i<count($agent);$i++) {
                if($value['id']==$agent[$i]){
                    $list[$key]['type'] = 1;
                    continue;
                }
            }
            }
        return[
            'code'=>0,
            'msg'=>'success',
            'list'=>[
                'data'=>$list,
                'count'=>$count,
            ],
        ];
    }
    public function save()
    {
        if (!$this->validate()) {
            return $this->getModelError();
        }
        $this->model->store_id = $this->store_id;
        $good = $this->good;

//        $st=$good[0];
//        for($i=1;$i<count($good);$i++){
//            $st = $st.','.$good[$i];
//        }
        $this->model->good = $good;
        if ($this->model->save())
            return [
                'code' => 0,
                'msg' => '保存成功',
            ];
        else
            return $this->getModelError($this->model);
    }

}